﻿using System.Threading;

namespace Present.Commands.Async.Actions.Decorators
{
    /// <summary>
    /// Cancels the existing execution before executing a new one
    /// </summary>
    public class CancelOnNewExecutionAsyncActionDecorator<TParameter, TResult> : AsyncActionDecorator<TParameter, TResult>
    {
        private ActionExecution<TParameter> currentExecution;

        public CancelOnNewExecutionAsyncActionDecorator(IAsyncAction<TParameter, TResult> innerTarget)
            : base(innerTarget)
        {
        }


        public override TResult DoWork(ActionExecution<TParameter> execution)
        {
            var toCancel = Interlocked.Exchange(ref currentExecution, execution);
            if (toCancel != null)
                toCancel.CancelRequested = true;

            return base.DoWork(execution);
        }

    }
}